<div class="hidden lg:block flex-none w-64 pl-8 mr-8">
    <div class="sticky top-20">
        <div class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-4">目录</div>
        <nav class="overflow-y-auto max-h-[calc(100vh-8rem)] pr-4 -mr-4 space-y-1 pageforge-scrollbar" id="table-of-contents">
            <% function renderTocItem(items) { %>
                <% items.forEach(item => { %>
                    <div class="pl-<%= (item.level - 1) * 4 %>">
                        <a href="#<%= item.slug %>"
                           class="block px-3 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800 rounded-md transition-colors duration-150 toc-link"
                           data-slug="<%= item.slug %>">
                            <%- item.text %>
                        </a>
                    </div>
                    <% if (item.children && item.children.length > 0) { %>
                        <% renderTocItem(item.children) %>
                    <% } %>
                <% }) %>
            <% } %>
            <% renderTocItem(page.toc) %>
        </nav>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const tocLinks = document.querySelectorAll('.toc-link');

        function updateActiveState() {
            const hash = window.location.hash.slice(1);  // 移除 # 符号
            tocLinks.forEach(link => {
                const slug = link.dataset.slug;
                // 先移除所有激活类
                link.classList.remove('text-gray-900', 'dark:text-gray-200', 'bg-gray-100', 'dark:bg-gray-800');
                link.classList.add('text-gray-600', 'dark:text-gray-400');

                // 仅为当前hash添加激活类
                if (slug === hash) {
                    link.classList.remove('text-gray-600', 'dark:text-gray-400');
                    link.classList.add('text-gray-900', 'dark:text-gray-200', 'bg-gray-100', 'dark:bg-gray-800');
                }
            });
        }

        // 仅在 hash 变化时更新状态，不需要监听滚动
        window.addEventListener('hashchange', updateActiveState);
        // 初始化状态
        updateActiveState();
    });
</script>